<script setup>
import { ref, computed, onMounted } from 'vue';
import { User } from "@/api"
import { ElMessage } from 'element-plus';
let imageUrl=ref('')
// 宏函数：声明props属性--外部数据
let props = defineProps({
  title:{
    type:String,
    defaults:'上传图片',
  }
});
// 宏函数：声明event事件
let emit = defineEmits(['update:imageUrl']);
onMounted(() => {
  load_img_cate();
  load_img(1);
})
// 加载分类列表
let img_cate = ref([])
let load_img_cate = async (name) => {
  let { status, msg, data } = await User.getImageCate({ name: name });
  if (status) {
    img_cate.value = data.list;
  }
}
// // 转化树形结构
// let tree_data=computed((img_cate)=>{
//     let cate_1st = img_cate.filter((item) => item.pid === 0);
//     let treeData = convert(cate_1st, img_cate);
//     return treeData;
// })

// function convert(arr, origin) {
//     return arr.map((parent) => {
//         let children = origin.filter((child) => parent.id === child.pid);
//         if (children.length) {
//             return { ...parent, children: convert(children, origin) };
//         } else {
//             return { ...parent };
//         }
//     });
// }


// 拉取图片数据
let img_count = ref(0);
let img_list = ref([]);
let load_img = async (page) => {
  let { status, msg, data } = await User.getImage({ page: page, limit: 18 })
  if (status) {
    img_count.value = data.count;
    img_list.value = data.list;
  }
}

// 打开弹窗
let is_dialog_open = ref(false);
let open_dialog = () => {
  is_dialog_open.value = true;
}
// 图片换页
let handle_change_page = (page) => {
  load_img(page)
}
// 搜索图片分类
let search_img_cate = ref('');
let handle_search_img_cate = async () => {
  load_img_cate(search_img_cate.value)
}
let checked_group = ref([]);
let handle_check_img = (dir) => {
  let isExist = checked_group.value.some((item) => { return item === dir });
  if (isExist) {
    checked_group.value.splice(checked_group.value.indexOf(dir), 1)
  } else {
    checked_group.value.push(dir)
  }
}
// 删除图片
let all_img = ref([]);
let handle_remove_img = async () => {
  let { status, msg, data } = await User.getImage({ limit: img_count.value })
  if (status) {
    all_img.value = data.list;
  }
  all_img.value.forEach((item) => {
    checked_group.value.forEach(async (dir) => {
      if (item.att_dir === dir) {
        
        let { status: re_status, msg: re_msg } = await User.remove_img({ids:item.att_id});
        if (re_status) {
          load_img()
        }
      }
    })
  })
}
let handle_use_img = () => {
  if (checked_group.value.length > 1) {
    ElMessage.error("只能选一张图片")
  } else {
    imageUrl.value = checked_group.value[0];
    is_dialog_open.value = false
    emit('update:imageUrl',imageUrl.value)
    console.log(imageUrl.value);
  }
}
</script>

<template>
  <el-card @click="open_dialog" class="picture">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-card>
  <el-dialog v-model="is_dialog_open" @close="is_dialog_open = false" width="1000px" :title="title">
    <el-row>
      <el-col style="border-right: 1px solid grey; padding-right: 5px;" :span="5">
        <el-input v-model="search_img_cate">
          <template #append>
            <el-button @click="handle_search_img_cate" type="primary">
              <el-icon>
                <Search></Search>
              </el-icon>
            </el-button>
          </template>
        </el-input>
        <div class="cate_list_item">
          <span>全部图片</span>
          <el-icon>
            <MoreFilled></MoreFilled>
          </el-icon>
        </div>
        <div v-for="item in img_cate" class="cate_list_item">
          <span>{{ item.name }}</span>
          <el-icon>
            <MoreFilled></MoreFilled>
          </el-icon>
        </div>
      </el-col>
      <el-col :span="19">
        <el-row>
          <el-button @click="handle_use_img" :disabled="checked_group.length === 0" type="primary">使用选中图片</el-button>
          <el-upload class="upload-demo" action="http://www.shop.net/adminapi/file/upload">
            <el-button type="primary">上传图片</el-button>
          </el-upload>

          <el-button @click="handle_remove_img" :disabled="checked_group.length === 0" type="primary">删除图片</el-button>
          <el-select clearable placeholder="图片移动至"
            :popper-options="{ modifiers: [{ name: 'computeStyles', options: { adaptive: false } }] }">
            <el-option v-for="item in img_cate" :label="item.name" :value="item.id" />
          </el-select>
        </el-row>
        <el-row>
          <div class="image-container">
            <div v-for="(image, index) in img_list" @click="handle_check_img(image.att_dir)" class="image-box relative">
              <el-image class="el-image" :class="{ onchecked_img: image.att_id }" style="width: 100px; height: 100px"
                :src="image.att_dir" />
              <div class="image-name">{{ image.real_name }}</div>
              <div v-show="checked_group.indexOf(image.att_dir) > -1" class="onchecked_icon"><span class="checked_num">{{
                checked_group.indexOf(image.att_dir) + 1 }}</span></div>
            </div>
          </div>
        </el-row>
        <el-row style="">
          <span>共{{ img_count }}条</span>
          <el-pagination @current-change="handle_change_page" background layout="prev, pager, next,jumper"
            :total="img_count * 10 / 18" />
        </el-row>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<style lang="less" scoped>
.image-container {
  width: 760px;
  display: flex;
  flex-wrap: wrap;

  .image-box {
    margin: 10px 10px;

    .el-image {
      cursor: pointer;
    }

    .image-name {
      width: 100px;
      white-space: nowrap;
      /* 文本不换行 */
      overflow: hidden;
      text-overflow: ellipsis;
      /* 文本溢出时显示省略号标记... */
    }
  }
}

.picture {
  cursor: pointer;
}

.relative {
  position: relative;
}

.onchecked_img {
  border: 1px solid red;
}

.onchecked_icon {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 100%;
  background-color: red;
  color: white;
}

.avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}

.cate_list_item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>